#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :month_report_table_page.py
# Time  :2025/4/24 9:17
# Email :fortunatedong@163.com
# Author:by Adonli
import base64
import json
from datetime import datetime
import re
from streamlit.components.v1 import html
import streamlit as st
import os
import webbrowser
from config import Header_space
from settings.report_table import load_report_table,save_report_table
import os
os.environ["STREAMLIT_SERVER_ENABLE_STATIC_SERVING"] = "true"
os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
Header_space()
st.subheader("月报明细", divider=True)
report_table_detail = load_report_table()
today = datetime.today()
current_year = today.year
current_month = today.month

# 创建临时目录存放HTML文件
if not os.path.exists("static"):
    os.makedirs("static")
if "report_table_search_button" not in st.session_state:
    st.session_state.report_table_search_button = False
def create_and_open_html(data):
    # 生成HTML头部和CSS样式
    html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>{data['REPORTTYPE']}报告 - {data['DATE']}</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style>
                :root {{
                    --ios-blue: #778899;
                    --ios-light-gray: #F2F2F7;
                    --ios-dark-gray: #1C1C1E;
                    --ios-card-bg: #FFFFFF;
                    --ios-border: #D1D1D6;
                    --ios-green: #34C759;
                    --ios-orange: #FF9500;
                }}

                body {{
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
                    line-height: 1.5;
                    color: var(--ios-dark-gray);
                    background-color: var(--ios-light-gray);
                    margin: 0;
                    padding: 20px;
                    min-height: 100vh;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }}

                .container {{
                    width: 100%;
                    max-width: 900px;
                    margin: 0 auto;
                }}

                .header {{
                    background-color: var(--ios-blue);
                    color: white;
                    padding: 16px 20px;
                    margin-bottom: 16px;
                    border-radius: 10px;
                    width: 100%;
                    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                }}

                .report-title {{
                    font-size: 20px;
                    font-weight: 600;
                    margin: 0 0 8px 0;
                    letter-spacing: 0.5px;
                }}

                .report-info {{
                    display: flex;
                    justify-content: space-between;
                    flex-wrap: wrap;
                    gap: 12px;
                    font-size: 14px;
                    opacity: 0.9;
                }}

                .report-info span {{
                    display: flex;
                    align-items: center;
                }}

                .report-info i {{
                    margin-right: 6px;
                    font-size: 12px;
                }}

                .report-container {{
                    background: var(--ios-card-bg);
                    border-radius: 10px;
                    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                    padding: 20px;
                    width: 100%;
                    overflow-x: auto;
                }}

                table {{
                    width: 100%;
                    border-collapse: collapse;
                    margin: 12px 0;
                    font-size: 14px;
                }}

                th, td {{
                    padding: 14px 16px;
                    text-align: left;
                    border-bottom: 1px solid var(--ios-border);
                }}

                th {{
                    background-color: var(--ios-blue);
                    color: white;
                    font-weight: 500;
                    position: sticky;
                    top: 0;
                    white-space: nowrap;
                }}

                tr:hover {{
                    background-color: rgba(0, 122, 255, 0.05);
                }}

                .status-completed {{
                    color: var(--ios-green);
                    font-weight: 500;
                }}

                .status-inprogress {{
                    color: var(--ios-orange);
                    font-weight: 500;
                }}

                .work-hour {{
                    text-align: right;
                    font-weight: 500;
                    width: 80px; /* 增加工时列宽度 */
                    color: var(--ios-dark-gray);
                }}
                
                .workload {{
                    text-align: right;
                    font-weight: 500;
                    width: 80px; /* 增加工时列宽度 */
                    color: var(--ios-dark-gray);
                }}

                .department-cell {{
                    font-weight: 500;
                    color: var(--ios-dark-gray);
                    white-space: nowrap;
                }}

                .type-cell {{
                    color: #636366;
                }}

                .long-text {{
                    max-width: 280px;
                    word-wrap: break-word;
                    line-height: 1.4;
                }}

                .footer {{
                    text-align: center;
                    margin-top: 24px;
                    color: #8E8E93;
                    font-size: 12px;
                    width: 100%;
                }}

                .no-data {{
                    text-align: center;
                    padding: 40px;
                    color: #8E8E93;
                    font-style: italic;
                }}
                .tooltip {{
                    position: relative;
                    display: inline-flex;
                    align-items: center;
                    cursor: help;
                }}
                
                .tooltip .tooltiptext {{
                    visibility: hidden;
                    position: absolute;
                    top: 100%;
                    left: 50%;
                    transform: translateX(-50%);
                    z-index: 9999;
                    
                    width: 260px;
                    max-width: 90vw;
                    padding: 12px;
                    margin-top: 10px;
                    
                    background-color: var(--ios-dark-gray);
                    color: white;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    
                    font-size: 13px;
                    line-height: 1.5;
                    text-align: left;
                    white-space: normal;
                    word-wrap: break-word;
                    
                    opacity: 0;
                    transition: opacity 0.2s ease, transform 0.2s ease;
                }}
                
                .tooltip:hover .tooltiptext {{
                    visibility: visible;
                    opacity: 1;
                    transform: translateX(-50%) translateY(5px);
                }}
                
                /* 添加小箭头 */
                .tooltip .tooltiptext::after {{
                    content: "";
                    position: absolute;
                    top: 100%;
                    left: 50%;
                    transform: translateX(-50%);
                    border-width: 8px;
                    border-style: solid;
                    border-color: transparent transparent var(--ios-dark-gray) transparent;
                }}

                                
                @media (max-width: 768px) {{
                    body {{
                        padding: 12px;
                    }}

                    .container {{
                        max-width: 100%;
                    }}

                    th, td {{
                        padding: 12px 10px;
                        font-size: 13px;
                    }}

                    .long-text {{
                        max-width: 280px;
                    }}
                }}
            </style>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1 class="report-title">{data['REPORTTYPE']}报告 - {data['DATE']}</h1>
                    <div class="report-info">
                        <span><i class="fas fa-user"></i> 作者: {data['AUTHOR']}</span>
                        <span><i class="fas fa-building"></i> 部门: {data['DEPARTMENT']}</span>
                        <span><i class="fas fa-calendar-alt"></i> 报告类型: {data['REPORTTYPE']}</span>
                    </div>
                </div>

                <div class="report-container">
        """

    # 检查是否有报告详情
    if not data['REPORTDETAIL']:
        html_content += """
                <div class="no-data">
                    <i class="fas fa-info-circle" style="font-size: 24px; margin-bottom: 10px;"></i>
                    <p>本月暂无工作记录</p>
                </div>
            """
    else:
        html_content += """
                <table>
                    <thead>
                        <tr>
                            <th><i class="fas fa-building"></i> 部门</th>
                            <th><i class="fas fa-tag"></i> 类型</th>
                            <th><i class="fas fa-tasks"></i> 工作内容</th>
                            <th><i class="fas fa-check-circle"></i> 状态</th>
                            <th><i class="fas fa-comment"></i> 效果/备注</th>
                            <th class="work-hour">
                                <span class="tooltip">
                                    <i class="fas fa-clock"></i> 节省工时/月
                                    <span class="tooltiptext">节省工时是以月为单位统计，每个项目因每月工作频次、瞬时工作量等因素可能发生变化，所以该值为预估数值、并非精准。</span>
                                </span>
                            </th>
                            <th class="workload"><i class="fas fa-clock"></i> 节省工作量</th>
                        </tr>
                    </thead>
                    <tbody>
            """

        # 添加报告详情行
        for detail in data['REPORTDETAIL']:
            # 根据状态设置不同的样式
            status_class = "status-completed" if "完成" in detail['finsh'] else "status-inprogress"

            html_content += f"""
                        <tr>
                            <td class="department-cell">{detail['department']}</td>
                            <td class="type-cell">{detail['type']}</td>
                            <td>{detail['detail'].replace('\n', '<br>')}</td>
                            <td class="{status_class}">{detail['finsh']}</td>
                            <td>{detail['effects'].replace('\n', '<br>')}</td>
                            <td class="work-hour">{detail['work_hour']}</td>
                            <td class="workload">{detail['workload']}</td>
                        </tr>
                """

        html_content += """
                    </tbody>
                </table>
            """

    html_content += """
                </div>

                <div class="footer">
                    <p>报告生成时间: <span id="datetime"></span></p>
                    <p><i class="fas fa-copyright"></i> 2025 公司名称. 保留所有权利.</p>
                </div>
            </div>

            <script>
                document.getElementById('datetime').textContent = new Date().toLocaleString();
            </script>
        </body>
        </html>
        """

    # 生成唯一的文件名
    filename = f"static/repor_table.html"

    # 写入HTML文件
    with open(filename, "w", encoding="utf-8") as f:
        f.write(html_content)

    # 用浏览器打开
    # webbrowser.open_new_tab(f"file://{os.path.abspath(filename)}")

    # st.components.v1.html(html_content, height=800, scrolling=True)
    js = f"""
    <script>
        window.open('http://172.16.0.25:8000/{filename}', '_blank');
    </script>
    """
    st.components.v1.html(js, height=0)

def search(report_table_detail, start_date=None, end_date=None, author=None, department=None, report_type=None):
    # 处理空字符串参数，将其视为None
    start_date = start_date if start_date else None
    end_date = end_date if end_date else None
    author = author if author else None
    department = department if department else None
    report_type = report_type if report_type else None

    filtered_reports = report_table_detail.copy()

    # 转换日期格式为YYYY-MM
    if start_date is not None:
        start_date = start_date.strftime("%Y-%m")  # 将datetime.date转换为YYYY-MM格式字符串
    if end_date is not None:
        end_date = end_date.strftime("%Y-%m")  # 将datetime.date转换为YYYY-MM格式字符串

    # 筛选日期范围
    if start_date is not None or end_date is not None:
        filtered_reports = [report for report in filtered_reports
                          if (start_date is None or report["DATE"] >= start_date) and
                             (end_date is None or report["DATE"] <= end_date)]
        # 检查是否有匹配的日期范围
        if not filtered_reports and (start_date is not None or end_date is not None):

            return {"code":404,"message":f"没有找到在{start_date if start_date else ''}到{end_date if end_date else ''}范围内的报告"}



    # 筛选作者
    if author is not None:
        author_exists = any(author == report["AUTHOR"] for report in filtered_reports)
        if not author_exists:
            return {"code": 404,"message": f"作者不存在: {author}"}
        filtered_reports = [report for report in filtered_reports if author == report["AUTHOR"]]

    # 筛选部门
    if department is not None:
        department_exists = any(department == report["DEPARTMENT"] for report in filtered_reports)
        if not department_exists:
            return {"code": 404, "message": f"部门不存在: {department}"}

        filtered_reports = [report for report in filtered_reports if department == report["DEPARTMENT"]]

    # 筛选报告类型
    if report_type is not None:
        report_type_exists = any(report_type == report["REPORTTYPE"] for report in filtered_reports)
        if not report_type_exists:
            return {"code": 404, "message": f"报告类型不存在: {report_type}"}

        filtered_reports = [report for report in filtered_reports if report_type == report["REPORTTYPE"]]
    return {"code": 200, "message": filtered_reports}



col1, col2, col3, col4, col5, col6 = st.columns(6)
with col1:
    start_date = st.date_input(":blossom:**开始日期**", format="YYYY-MM-DD",value=None)
with col2:
    end_date = st.date_input(":blossom:**结束日期**", format="YYYY-MM-DD",value=None)
with col3:
    author = st.text_input(":blossom:**汇报人**")
with col4:
    department_option = ("项目开发部", "运营部", "渠道事业部", "电商部", "终端事业部", "财务部")
    department = st.selectbox(":blossom:**部门**", department_option, index=None, placeholder="选择部门")
with col5:
    type = ("日报", "月报", "半年报", "年报")
    report_type = st.selectbox(":blossom:**报表类型**", type, index=None, placeholder="选择类型")
with col6:
    col6_col1, col6_col2, col6_col3= st.columns(3)
    with col6_col2:
        st.write("")
        report_table_search_button = st.button("**搜索**")
        if report_table_search_button:
            st.session_state.report_table_search_button = True
            report_table_detail_result = search(report_table_detail, start_date, end_date, author, department, report_type)

st.divider()
colms = st.columns((1, 1, 1, 1, 1))
fields = ["日期", '汇报人', '部门', '报告类型', "查看"]
for col, field_name in zip(colms, fields):
    # header
    col.write(f"**{field_name}**")
if st.session_state.report_table_search_button:
    if report_table_detail_result["code"] == 200:
        report_table_detail = report_table_detail_result["message"]
        st.session_state.report_table_search_button = False
    else:
        st.error(report_table_detail_result["message"])
        st.session_state.report_table_search_button = False
        st.stop()

for i, row in enumerate(report_table_detail[:8]):
    table_col1, table_col2, table_col3, table_col4, table_col5 = st.columns(5)
    DATE = row["DATE"]
    AUTHOR = row["AUTHOR"]
    DEPARTMENT = row["DEPARTMENT"]
    REPORTTYPE = row["REPORTTYPE"]
    table_col1.write(DATE)
    table_col2.write(AUTHOR)
    table_col3.write(DEPARTMENT)
    table_col4.write(REPORTTYPE)
    table_button = table_col5.button("查看报告",key=DATE)
    if table_button:
        # st.write(row)
        create_and_open_html(row)
